<template>
  <div>
      <el-drawer
              v-model="question.testdialog"
              :title="question.title"
              :close-on-click-modal="false"
              direction="rtl"
              size="50%"
              @close="close"
            >
              <div class="choosenav">
                <el-radio-group v-model="test.type">
                  <el-radio label="单选题">单选题</el-radio>
                  <el-radio label="多选题">多选题</el-radio>
                  <el-radio label="判断题">判断题</el-radio>
                  <el-radio label="填空题">填空题</el-radio>              
                  <el-radio label="问答题">问答题</el-radio>
                </el-radio-group>
              </div>
              <div class="stem">
                <span>题干</span>
                <div style="border: 1px solid #ccc">
                  <Toolbar
                    style="border-bottom: 1px solid #ccc"
                    :editor="editorRef"
                    :defaultConfig="toolbarConfig"
                    :mode="mode"
                  />
                  <Editor
                    style="height: 200px; overflow-y: hidden;"
                    v-model="test.title"
                    :defaultConfig="editorConfig"
                    :mode="mode"
                    @onCreated="handleCreated"
                  />
                </div>
              </div>
              <!-- 选则 -->
            <div v-show="test.type==='单选题'||test.type==='多选题'">
               <!-- 选项 -->
               <div class="choosebox">
                <span>选项</span>
                <div>
                    <div class="textarea" 
                    v-for="(item,index) in test.answers"
                    :key="index"
                    >
                      <span>{{item.answerno}}:</span>
                      <el-input  type="textarea" v-model="item.content"/>
                      <el-icon @click="answerDel(index)"><CircleClose /></el-icon>
                  </div>
                 
                </div>
                
              </div>
              <div>
                  <el-icon class="Plus" @click="answersAdd"><CirclePlus /></el-icon>
              </div>
              <div v-show="test.type==='单选题'">
                <div class="answer">
                  <span>正确答案</span>
                  <div class="mb-2 flex items-center text-sm" >
                    <el-radio-group  v-model="test.answer" class="ml-4">
                      <el-radio  size="large"
                        v-for="(item,index) in test.answers"
                        :key="index"
                        :label="item.answerno"
                      >{{item.answerno}}</el-radio>
                    </el-radio-group>
                  </div>
                </div>
              </div >
              <div  v-show="test.type==='多选题' " >
                <div class="answer" >
                  <span>正确答案</span>
                  <div class="mb-2 flex items-center text-sm">
                    <el-checkbox-group v-model="test.checked" class="ml-4">
                      <el-checkbox 
                      v-for="(item,index) in test.answers"
                        :key="index"
                        :label="item.answerno"
                      >{{item.answerno}}</el-checkbox>
                     
                    </el-checkbox-group>
                </div>
              </div>
            </div>
            </div>
            <!-- 判断 -->
            <div v-show="test.type==='判断题'">
                <div class="answer">
                  <span>正确答案</span>
                  <div style="margin-top: 20px">
                    <el-radio-group v-show="test.type==='判断题'">
                      <el-radio-button label="正确" />
                      <el-radio-button label="错误" />
                    </el-radio-group>
                  </div>
                </div>
            </div>
            <!-- 填空 问答 -->
            <div v-show="test.type==='填空题'|| test.type==='问答题'">
              <div class="answer">
                  <span>解析</span>
                  <div >
                    <el-input  type="textarea"/>
                  </div>
                </div>
            </div>
              <div class="scores">
                <span>分值：</span>
                <div>
                  <el-input-number
                    v-model="test.scores"
                    class="mx-4"
                    :min="1"
                    :max="10"
                    controls-position="right"
                    @change="handleChange"
                  />
                </div>
              </div>
              <div class="btn">
                <el-button type="primary" @click="save">保存</el-button>
                <el-button v-show="test.id===0">保存并继续</el-button>
                <el-button>取消</el-button>
              </div>
            </el-drawer>
  </div>
</template>

<script setup lang="ts">
import {  ref,reactive,onMounted,shallowRef,onBeforeUnmount,toRefs,watch} from "vue";
import { CircleClose,CirclePlus } from '@element-plus/icons-vue'
import { ElDrawer, ElMessage} from 'element-plus'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { getENStr } from "../../utils/utils";

import _ from 'lodash'
const emits = defineEmits(['add',"isOpen"])
const props = withDefaults(defineProps<{
  question:{
      id:number,
      testdialog:boolean,
      title:string,
      params:object
  }
}>(), {
//    question:{
//         testdialog:false,
//         title:''
//    }
})

let testdialog=ref(false)
// 表单数据
const data =reactive({
  test:{
      id:0,
      type:'单选题',
      title:'',
      checked:[],
      answer:'',//正确答案
      explains: "",//解析
      scores: 0, // 分值
      answers: [
          { answerno: "A", content: "" },
          { answerno: "B", content: "" },
          { answerno: "C", content: "" },
          { answerno: "D", content: "" },
      ],
  }
})
const { test} = toRefs(data);
const mode=ref()
// 获取数组下一个字符
const getENNextStr = (str: string, end: string= 'F') => {
  let arr =  getENStr(end) // ['A', 'B',.. ,'F']
  let index = arr.findIndex(s => s === str)
  if (arr[index] === end) {
    ElMessage.error('已到达最大选项数')
     return false
  }
  return arr[index + 1]
} 
// 添加选项
const answersAdd = () => {
let curOption = test.value.answers.length ? test.value.answers[test.value.answers.length - 1].answerno : '@'
  // 获取下一个可添加的选项
  let nextOption = getENNextStr(curOption)
  if (!nextOption) {
      ElMessage.error('最大只能添加到' + curOption)
      return
  }
  // console.log('当前添加的选项', nextOption)
  // 添加新的项
  test.value.answers.push({
      answerno: nextOption,
      content: ''
  })
};
// 删除答案列表
const answerDel=(index:number)=>{
// console.log(test.value.answers.length);
if (index < test.value.answers.length - 1) {
  for (var i = index; i < test.value.answers.length - 1; i++) {
    test.value.answers[i].content = test.value.answers[i + 1].content;
  }
}
test.value.answers.splice(test.value.answers.length - 1, 1);
}
// 监听数据变化
watch(()=>props.question,question=>{
  // console.log(question);
  if(question.testdialog&&question.id>0){
      test.value=Object.assign({},test.value,question.params)
      question.title='试题修改'     
  }
  
},{immediate:true,deep:true})

// 保存 
const save=()=>{
emits('add',test.value)
}
// 清空
const close = () => {
// 数组下标0 弹出是否关闭   1 加载
emits("isOpen", [false, false]);
};


// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('<p>hello</p>')

// 模拟 ajax 异步获取内容
onMounted(() => {
  setTimeout(() => {
      valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
  }, 1500)
})
const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor:any) => {
editorRef.value = editor // 记录 editor 实例，重要！
}
const handleChange = (value: number) => {
console.log(value)
}
</script>

<style scoped lang="less">
.choosebox{
    display: flex;
    width: 600px;
    margin: 10px;
    line-height: 50px;
    .textarea{
      display: flex;
      justify-content: space-between;
      line-height: 50px;
      padding: 10px;
      color: #000;
      width: 300px;
      .el-textarea{
        width: 260px;
        height: 20px;
      }
      .el-icon {
        cursor: pointer;
        color: red;
        display: block;
        line-height: 50px;
        font-size: 24px;
      }
      
    }
  }
  .Plus{
    cursor: pointer;
        font-size: 30px; 
        margin-left: 50px;
        color: rgb(89, 160, 255);
  }
  .answer{
    display: flex;
    padding: 10px;
  }
  .mb-2 {
    padding: 10px;
  }
  .scores{
    display: flex;
  }
  .btn{
    margin: 30px;
  }
  .stem{
    width: 900px;
    white-space: nowrap;
    // height: 200px;
    display: flex;
  }

</style>